package com.pony.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pony.common.LoginDto;
import com.pony.common.Result;
import com.pony.entity.User;
import com.pony.service.UserService;
import com.pony.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author malf
 * @description 登录接口
 * 接受账号密码，然后把用户的id生成jwt，返回给前段，为了后续的jwt的延期，把jwt放在header上
 * @date 2021/5/22
 * @project springboot_blog
 */
@RestController
public class AccountController {

	@Resource
	JwtUtils jwtUtils;
	@Resource
	UserService userService;

	/**
	 * 默认账号密码：pony / 111111
	 */
	@CrossOrigin
	@PostMapping("/login")
	public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
		User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
		Assert.notNull(user, "用户不存在");
		if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
			return Result.fail("密码错误！");
		}
		String jwt = jwtUtils.generateToken(user.getId());
		response.setHeader("Authorization", jwt);
		response.setHeader("Access-Control-Expose-Headers", "Authorization");
		return Result.success(MapUtil.builder()
				.put("id", user.getId())
				.put("username", user.getUsername())
				.put("avatar", user.getAvatar())
				.put("email", user.getEmail())
				.map()
		);
	}

	// 退出
	@GetMapping("/logout")
	@RequiresAuthentication
	public Result logout() {
		SecurityUtils.getSubject().logout();
		return Result.success(null);
	}

}
